const db = require('../db/index')
exports.addCourse = (req, res) => {
  const course = req.body
  const sqlStr = `select * from course where cid=?`
  db.query(sqlStr, course.cid, (err, results) => {
    if (err) {
      return res.cc(err)
    }
    if (results.length) {
      return res.cc('课程编号已被占用，请更换其他编号！')
    }
    const sql = `insert into course set ?`
    db.query(sql, { ...course }, (err, results) => {
      if (err) {
        return res.cc(err)
      }
      if (results.affectedRows !== 1) {
        return res.cc('添加课程失败，请稍后再试！')
      }
      res.cc('注册成功！', 0)
    })
  })
}
exports.getCourse = (req, res) => {
  const sqlStr = 'select * from course'
  db.query(sqlStr, (err, results) => {
    if (err) {
      return res.cc(err)
    }
    if (!results.length) {
      return res.cc('获取课程信息失败！')
    }
    res.send({
      status: 0,
      message: '获取课程信息成功！',
      data: results
    })
  })
}
exports.updateCourse = (req, res) => {
  const sqlStr = 'update course set ? where cid=?'
  db.query(sqlStr, [req.body, req.body.cid], (err, results) => {
    if (err) {
      return res.cc(err)
    }
    if (results.affectedRows !== 1) {
      return res.cc('修改课程失败！')
    }
    res.cc('修改课程成功！', 0)
  })
}
exports.deleteCourse = (req, res) => {
  let sqlStr = 'delete from course where cid=?'
  db.query(sqlStr, req.body.cid, (err, results) => {
    if (err) {
      return res.cc(err)
    }
    if (results.affectedRows !== 1) {
      return res.cc('删除课程失败！')
    }
    res.cc('删除课程成功！', 0)
  })
}